﻿using System;

namespace OrkutAPILibrary.Enums
{
    /// <summary>
    /// Provides methods for converting from enum to string and back
    /// </summary>
    public static class StringEnum
    {
        /// <summary>
        /// Gets the string value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string GetStringValue(Enum value)
        {
            string output = null;
            var type = value.GetType();
            var fi = type.GetField(value.ToString());
            var attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[];
            if (attrs != null)
                if (attrs.Length > 0)
                {
                    output = attrs[0].Value;
                }
            return output;
        }

        /// <summary>
        /// Gets the enum value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static CountryName GetEnumValue(string value)
        {
            CountryName? name = null;
            foreach (CountryName countryName in Enum.GetValues(typeof(CountryName)))
            {
                string output = String.Empty;
                name = countryName;
                var fi = typeof(CountryName).GetField(countryName.ToString());
                var attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[];
                if (attrs != null)
                    if (attrs.Length > 0)
                    {
                        output = attrs[0].Value;
                    }
                if (output.Equals(value.ToUpper()))
                {
                    break;
                }
            }

            return name.Value;
        }
    }
}